package com.xtc.netty.protocol.http.xml.handler;

import com.xtc.netty.protocol.http.model.Address;
import com.xtc.netty.protocol.http.model.Order;
import com.xtc.netty.protocol.http.xml.HttpXmlRequest;
import com.xtc.netty.protocol.http.xml.HttpXmlResponse;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

import java.util.ArrayList;
import java.util.List;

import static io.netty.handler.codec.http.HttpUtil.isKeepAlive;

/**
 * @author Administrator
 */
public class HttpXmlServerHandler extends SimpleChannelInboundHandler<HttpXmlRequest> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpXmlRequest xmlRequest) throws Exception {
        HttpRequest request = xmlRequest.getRequest();
        Order order = (Order) xmlRequest.getBody();
        System.out.println("Http server receive request :" + order);

        doBusiness(order);

        ChannelFuture future = ctx.writeAndFlush(new HttpXmlResponse(null, order));
        if (!isKeepAlive(request)) {
            future.addListener(new GenericFutureListener<Future<? super Void>>() {
                @Override
                public void operationComplete(Future<? super Void> future) throws Exception {
                    System.out.println("关闭连接：" + ctx.channel().remoteAddress());
                    ctx.close();
                }
            });
        }
    }

    private void doBusiness(Order order) {
        order.getCustomer().setFirstName("波");
        order.getCustomer().setLastName("结衣");

        List<String> midNames = new ArrayList<>();
        midNames.add("小泽玛利亚");
        order.getCustomer().setMiddleNames(midNames);

        Address address = order.getBillTo();
        address.setCity("东京");
        address.setCountry("黑石");
        address.setPostCode("123145");

        order.setShipTo(address);
        order.setBillTo(address);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
